#include "Switch.h"
#include "Timer.h"
#include "IO.h"
#define SW_DEBOUNCE_TIMES (10)
STRSWConfig g_sw_stConfig[SW_SWITCH_NUM] = 
{
	
    {P_SW_X00_PORT, P_SW_X00_PIN, 8, 1}, // KY_NUM0
    {P_SW_X01_PORT, P_SW_X01_PIN, 8, 0}, // KY_NUM0 
		{P_SW_X02_PORT, P_SW_X02_PIN, 8, 0}, // KY_NUM0
		{P_SW_X03_PORT, P_SW_X03_PIN, 8, 0}, // KY_NUM0
};
SWStatusType g_sw_stRegs;
void fnSW_Init(void);
void fnSW_RealTime(void);
void fnSW_Clear(void);
void fnSW_Init(void)
{
	U8 i;
	for(i = 0; i< SW_SWITCH_NUM; i++)  //
	{
		if(i == 0){
			SET_IO_IN_PULLDOWN(g_sw_stConfig[i].port, g_sw_stConfig[i].pin);
		}else{
			SET_IO_IN_PULLUP(g_sw_stConfig[i].port, g_sw_stConfig[i].pin);
		}
	}
	memset(&g_sw_stRegs, 0, sizeof(g_sw_stRegs));
	g_sw_stRegs.m_uiReadyTimer = 250;
}
U8 fnSW_GetState(U8 keynum)
{
    U8 uState=0;
		
		if(GET_IO_STA(g_sw_stConfig[keynum].port, g_sw_stConfig[keynum].pin) == g_sw_stConfig[keynum].level){
			uState = 1;
		}
    return uState;
}


void fnSW_RealTime(void)
{
    U8 i, temp;
	if(g_tm_stTimerFlag.Bits.bTimer8ms)
	{
		if(g_sw_stRegs.m_uiReadyTimer)
		{
			g_sw_stRegs.m_uiReadyTimer --;
		}
		for(i = 0; i< SW_SWITCH_NUM; i++)
		{
			temp = fnSW_GetState(i);
			if(temp != g_sw_stRegs.m_uchLevel[i])
			{
				g_sw_stRegs.m_uchCount[i] ++;
			}
			else
			{
				g_sw_stRegs.m_uchCount[i] = 0;
			}
			if(g_sw_stRegs.m_uchCount[i] > g_sw_stConfig[i].debounce)
			{
				g_sw_stRegs.m_uchLevel[i] = temp;
				g_sw_stRegs.m_uchTrigger[i] = TRUE;
				g_sw_stRegs.m_uchCount[i] = 0;
			}
		}
  }
	

	
}
void fnSW_Clear(void)
{
	U8 i;
	for(i = 0; i< SW_SWITCH_NUM; i++)
	{
	    g_sw_stRegs.m_uchTrigger[i] = 0;
	}
}
